package com.zzl.study.auth.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * @author: zhangzl
 * @date: 2023/12/8 15:53
 * @version: 1.0
 * @description:
 */
public class SecretUtils {

    /**
     * 加密加密算法：AES
     */
    public static final String ALGORITHM_NAME_AES = "AES";

    /**
     * 对称加密算法：DES
     */
    public static final String ALGORITHM_NAME_DES = "AES";

    /**
     * 生成密钥
     *
     * @param algorithmName 加密算法
     * @return 密钥
     */
    public static String generateSecretKey(String algorithmName) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithmName);
            keyGenerator.init(new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            String key = Hex.encodeHexString(secretKey.getEncoded());
            return new String(Base64.encodeBase64(key.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new RuntimeException("通过加密算法" + algorithmName + "生成密钥出错!", e);
        }
    }

}
